import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:web_socket_channel/io.dart';

class HuYaLiveDanmakuPage extends StatefulWidget {
  final int roomId;
  HuYaLiveDanmakuPage(this.roomId);
  @override
  _LiveDanmakuPageState createState() => _LiveDanmakuPageState();
}

class _LiveDanmakuPageState extends State<HuYaLiveDanmakuPage>
    with AutomaticKeepAliveClientMixin<HuYaLiveDanmakuPage> {
  Timer timer;
  IOWebSocketChannel _channel;
  int totleTime = 0;
  List _messageList = [];
  ScrollController _scrollController = ScrollController();

  _scrollToBottom() {
    _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
  }

  @override
  void initState() {
    initLive();
    setListener();
    super.initState();
  }

  @override
  void dispose() {
    timer?.cancel();
    _channel?.sink?.close();
    super.dispose();
  }

  @override
  bool get wantKeepAlive => true;

  //初始化
  void initLive() {
    _channel = IOWebSocketChannel.connect("wss://cdnws.api.huya.com/");
    timer = Timer.periodic(Duration(seconds: 45), (callback) {
      totleTime += 45;
      print("时间: $totleTime s");
    });
  }
  //发送心跳包
  void heartBeat() {
    String heartbeat = 'type@=mrkl/';
    _channel.sink.add(encode(heartbeat));
  }
  //设置监听
  void setListener() {
    _channel.stream.listen((msg) {
      Uint8List list = Uint8List.fromList(msg);
      decode(list);
    });
  }
  void addDanmaku(LiveDanmakuItem item) {
    setState(() {
      _messageList.add(item);
    });
  }
//解析websocket
  @override
  Widget build(BuildContext context) {
    super.build(context);
    WidgetsBinding.instance.addPostFrameCallback((_) => _scrollToBottom());
    return ListView.builder(
        controller: _scrollController,
        itemCount: _messageList.length,
        padding: const EdgeInsets.only(left: 5, top: 2, right: 5),
        // reverse: true,
        shrinkWrap: true,
        itemBuilder: (context, i) {
          Widget item;
          if (_messageList[i] is LiveDanmakuItem) {
            LiveDanmakuItem huYaDanmakuItem = _messageList[i];
            item = Container(
              padding: EdgeInsets.all(5),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    " ${huYaDanmakuItem.name} : ",
                    style: TextStyle(fontWeight: FontWeight.w700),
                  ),
                  Expanded(
                    child: Text(
                      "${huYaDanmakuItem.msg}",
                    ),
                  )
                ],
              ),
            );
          }
          return item;
        });
  }
  decode(Uint8List list){

  }
  Uint8List encode(String msg) {
    ByteData header = ByteData(12);
    //定义协议头
    header.setInt32(0, msg.length + 9, Endian.little);
    header.setInt32(4, msg.length + 9, Endian.little);
    header.setInt32(8, 689, Endian.little);
    List<int> data = header.buffer.asUint8List().toList();
    List<int> msgData = utf8.encode(msg);
    data.addAll(msgData);
    //结尾 \0 协议规定
    data.add(0);
    return Uint8List.fromList(data);
  }


}


class LiveDanmakuItem {
  String name;
  String msg;
  LiveDanmakuItem(this.name, this.msg);
}
